package com.cn.yugan.Fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.cn.yugan.Activity.ArticleInfoActivity;
import com.cn.yugan.Cons.ArticleConstants;
import com.cn.yugan.Cons.LoginConstants;
import com.cn.yugan.Engine.Adapter.ArticleListViewAdpater;
import com.cn.yugan.Engine.Http.GetList;
import com.cn.yugan.Engine.Json.ArticleListJson;
import com.cn.yugan.Engine.Beans.ArticleListInfo;
import com.cn.yugan.mobile.R;
import com.cn.yugan.Utils.ToastUtils;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.apache.http.Header;

import java.util.ArrayList;

/**
 * Created by Rover on 2016/7/17 .
 * Email 357319517@qq.com
 */

public class IndexFragment extends Fragment {
    private ArrayList<ArticleListInfo> mlist;
    private PullToRefreshListView mPullRefreshListView;
    private ArticleListViewAdpater madapter;
    private int Loginmode = LoginConstants.LOGIN_GUEST;
    private Context context;
    private String type;
    private int page = 1;
    private String SortMode;

    public IndexFragment(Context context, String type, String SortMode) {
        this.context = context;
        this.type = type;
        this.SortMode = SortMode;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//        View view = inflater.inflate(R.layout.frag_error, null);
//        Button button = (Button) view.findViewById(R.id.frag_error_bt);
//        TextView textView = (TextView) view.findViewById(R.id.frag_error_tv);
//        textView.setText(Html.fromHtml(getResources().getString(R.string.error1) + "<br>" + getResources().getString(R.string.error2) + "<br>" + getResources().getString(R.string.error3)));
//        button.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //刷新逻辑
//                GetList.ArticleListAsyncHttpClient(context, context.getString(R.string.serverurl) + context.getString(R.string.list), type, ArticleConstants.time, 1, new AsyncHttpResponseHandler() {
//                    @Override
//                    public void onSuccess(int i, Header[] headers, byte[] bytes) {
//                        //  LogUtils.d(new String(bytes, "UTF-8"));
//                        mlist = ArticleListJson.json2list(bytes);
//                    }
//
//                    @Override
//                    public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
//                        ToastUtils.show(context, "服务器未响应");
//                    }
//                });
//            }
//        });
//        if (mlist.isEmpty()) {
//            View view = inflater.inflate(R.layout.frag_loading, null);
//            GifView gv = (GifView) v.findViewById(R.id.frag_loading_pro);
//            gv.setMovieResource(R.raw.loading);
//            return view;
//        } else {
//        }

        mlist = new ArrayList<>();
        GetList.ArticleListAsyncHttpClient(context, context.getString(R.string.serverurl) + context.getString(R.string.list), type, SortMode, 1, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int i, Header[] headers, byte[] bytes) {
                        //  LogUtils.d(new String(bytes, "UTF-8"));
                        mlist = ArticleListJson.json2list(bytes);
                        madapter.refreshList(mlist);
                        madapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                        ToastUtils.show(context, "服务器未响应");
                    }
                }

        );
        View view = inflater.inflate(R.layout.frag_normal, null);
        mPullRefreshListView = (PullToRefreshListView) view.findViewById(R.id.frag_normal_lv);

        madapter = new ArticleListViewAdpater(context, mlist, type);
        mPullRefreshListView.setAdapter(madapter);
        mPullRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        mPullRefreshListView.setOnRefreshListener(new OnRefreshListener());
        ILoadingLayout startLabels = mPullRefreshListView
                .getLoadingLayoutProxy(true, false);
        startLabels.setPullLabel("下拉我帮你刷新(*^__^*) ");// 刚下拉时，显示的提示    
        startLabels.setRefreshingLabel("鱼干娘帮你刷新中...");// 刷新时    
        startLabels.setReleaseLabel("放开我啊，臭流氓((‵□′)) ");// 下来达到一定距离时，显示的提示  

        ILoadingLayout endLabels = mPullRefreshListView.getLoadingLayoutProxy(
                false, true);
        endLabels.setPullLabel("上拉我帮你加载(*^__^*) ");// 刚下拉时，显示的提示    
        endLabels.setRefreshingLabel("鱼干娘寻找中...");// 刷新时    
        endLabels.setReleaseLabel("放开我啊，臭流氓((‵□′)) ");// 下来达到一定距离时，显示的提示

        mPullRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (Loginmode == LoginConstants.LOGIN_NORMAL) {
                    ArticleListInfo articleListInfo = (ArticleListInfo) madapter.getItem(position - 1);
                    //相关操作
                    Intent intent = new Intent(getActivity(), ArticleInfoActivity.class);
                    intent.putExtra("aid", articleListInfo.getAid());
                    startActivity(intent);
                } else {
                    Toast.makeText(getActivity(), "鱼干娘的小秘密不会让我不认识的人看见喔！", Toast.LENGTH_SHORT).show();
                }
            }
        });
        return view;

    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    private class OnRefreshListener implements PullToRefreshBase.OnRefreshListener<ListView> {
        @Override
        public void onRefresh(final PullToRefreshBase<ListView> refreshView) {
            if (mPullRefreshListView.isHeaderShown()) {
                String label = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                refreshView.getLoadingLayoutProxy()
                        .setLastUpdatedLabel(label);
                //下拉加载逻辑
                GetList.ArticleListAsyncHttpClient(context, context.getString(R.string.serverurl) + context.getString(R.string.list), type, ArticleConstants.time, 1, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int i, Header[] headers, byte[] bytes) {
                        //  LogUtils.d(new String(bytes, "UTF-8"));
                        mlist = ArticleListJson.json2list(bytes);
                        madapter.refreshList(mlist);
                        madapter.notifyDataSetChanged();
                        refreshView.onRefreshComplete();
                    }

                    @Override
                    public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                        ToastUtils.show(context, "服务器未响应");
                        refreshView.onRefreshComplete();
                    }
                });

            } else if (mPullRefreshListView.isFooterShown()) {
                //上拉加载逻辑
                page++;
                GetList.ArticleListAsyncHttpClient(context, context.getString(R.string.serverurl) + context.getString(R.string.list), type, ArticleConstants.time, page, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int i, Header[] headers, byte[] bytes) {
                        //  LogUtils.d(new String(bytes, "UTF-8"));
                        mlist = ArticleListJson.json2list(bytes);
                        if (mlist == null) {
                            page--;
                        } else {
                            madapter.addList(mlist);
                            madapter.notifyDataSetChanged();
                        }
                        refreshView.onRefreshComplete();
                    }

                    @Override
                    public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                        ToastUtils.show(context, "服务器未响应");
                        page--;
                        refreshView.onRefreshComplete();
                    }
                });
            }
        }

    }

    public void setLoginMode(int Loginmode) {
        this.Loginmode = Loginmode;
    }

    public void uirefresh() {
        madapter.notifyDataSetChanged();
    }

    public void SetSortMode(String SoftMode) {
        this.SortMode = SoftMode;
        GetList.ArticleListAsyncHttpClient(context, context.getString(R.string.serverurl) + context.getString(R.string.list), type, SortMode, 1, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int i, Header[] headers, byte[] bytes) {
                        //  LogUtils.d(new String(bytes, "UTF-8"));
                        mlist = ArticleListJson.json2list(bytes);
                        madapter.refreshList(mlist);
                        madapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                        ToastUtils.show(context, "服务器未响应");
                    }
                }

        );
    }

    public String gettype() {
        return this.type;
    }
}
